<template>
  <div style="position: relative;">
    <transition name="fade" mode="out-in">
      <div class="placeholder-text" v-if="!isShowHolder">
        <span>1、商品描述说明</span><br />
        <span>2、可上传商品的细节图</span>
      </div>
    </transition>

    <div 
    class="rich-text" 
    ref="myRichText" 
    contentEditable=true 
    @blur="richTextBlur()" 
    @focus="richTextFocus()">
    </div>

    <div class="editor-custom-btn-container">
      <!-- 上传图片 -->
      <div class="add-imgs">
        <el-upload
            class="avatar-uploaders"
            :action="BaseAPI"
            :headers="headers"
            :data="queryData"
            :multiple="true"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handError">
            <div class="add-img">
                <div class="img-log"></div>
                <div class="up-img">{{loading ? '上传中...' : '图片/视频'}}</div>
            </div>
        </el-upload>
      </div>
    </div>
    <div @click="getContent()">获取文本内容</div>
  </div>
  
</template>

<script>
import { getLocalStorage } from '@/utils/cookie.js'
export default {
  data() {
    return {
      BaseAPI: process.env.BASE_API + 'api-file/files-upload',
      BaseIMG: process.env.BASE_IMG,
      queryData: {
          imgType: 'goods',
          userType: this.$store.getters.userData.companyType || ''
      },
      headers: {
          Authorization: ''
      },
      selectText: '',
      rangeNode: '',
      textContent: '',
      isShowHolder: false,
      loading3: false
    }
  },
  created() {
    this.headers.Authorization = getLocalStorage('token')
  },
  methods: {
    // 自定义富文本一下方法
    richTextFocus() {
      this.isShowHolder = true
    },
    // 获取光标位置
    richTextBlur() {
      this.selectText = window.getSelection();    
      this.rangeNode = this.selectText.getRangeAt(0);
      this.rangeNode.deleteContents();
      if (!this.$refs.myRichText.innerHTML.replace(/\s/g, '') || this.$refs.myRichText.innerHTML == '<br>') {
        this.isShowHolder = false
      } else {
        this.isShowHolder = true
      }
    },
    // 在光标位置添加内容
    insertHtmlAtCaret(htmlFile, type) {
      let flage = !this.$refs.myRichText.innerHTML.replace(/\s/g, '')
      if (window.getSelection) {
        // IE9 and non-IE
        if (this.selectText.getRangeAt && this.selectText.rangeCount) {
            var el = document.createElement("div");
            
            if (type) {
              const brNode = document.createElement('br')
              const brNode1 = brNode.cloneNode();
              el.appendChild(brNode)
              el.appendChild(htmlFile)
              el.appendChild(brNode1)
            } else {
              const brNode = document.createElement('br')
              const brNode1 = brNode.cloneNode();
              if (!flage) {
                el.appendChild(brNode)
              }
              el.appendChild(htmlFile)
              el.appendChild(brNode1)
            }
            
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            this.rangeNode.insertNode(frag);
            // Preserve the selection
            if (lastNode) {
              this.rangeNode = this.rangeNode.cloneRange();
              this.rangeNode.setStartAfter(lastNode);
              this.rangeNode.collapse(true);
              this.selectText.removeAllRanges();
              this.selectText.addRange(this.rangeNode);
            }
        }
      } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(htmlFile);
      }
      this.textContent = this.$refs.myRichText.innerHTML
    },
    // 最终获取内容
    getContent() {
      // 正则清楚文本中除img\video标签以外的所有html标签
      var contentText = this.$refs.myRichText.innerHTML.replace(/<(?!img|video|\/video).*?>/g, "")
      var imgList = [] // 图片列表
      var videoList = [] // 视频列表
      // 获取img 属性linkes的值
      contentText.replace(/<img [^>]*links=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
        imgList.push(capture)
      });
      // 获取video 属性linkes的值
      contentText.replace(/<video [^>]*links=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
        videoList.push(capture)
      });
      contentText = contentText.replace(/<img.*?src=[\"|\']?(.*?)[\"|\']*?>/gi, '[图片]')
      contentText = contentText.replace(/<[^>]*>|<\/[^>]*>/gm, '[视频]')
      let falge = contentText.lastIndexOf('[图片]') === contentText.length - 4
      let imgContArr = contentText.split('[图片]')
      let imgArrList = []
      let zongFileList = []
      for (let i = 0; i < imgContArr.length - 1; i++) {
        if (imgContArr[i] !== '') {
          imgArrList.push({
            type: 0,
            content: imgContArr[i]
          })
        }
        imgArrList.push({
          type: 1,
          content: imgList[i]
        })
      }

      if (!falge) {
        imgArrList.push({
          type: 0,
          content: imgContArr[imgContArr.length - 1]
        })
      }


      for (let j = 0; j < imgArrList.length; j++) {
        if (imgArrList[j].type === 0) {
          if (imgArrList[j].content.indexOf('[视频]') !== -1) {
            let falges = imgArrList[j].content.lastIndexOf('[视频]') === imgArrList[j].content.length - 4
            let txtConArr = imgArrList[j].content.split('[视频][视频]')
            for (let k = 0; k < txtConArr.length - 1; k++) {
              if (txtConArr[k] !== '') {
                zongFileList.push({
                  type: 0,
                  content: txtConArr[k]
                })
              }
              let videoFile = videoList.shift()
              zongFileList.push({
                type: 2,
                content: videoFile
              })
            }
            if (!falges) {
              let videoFile = videoList.shift()
              zongFileList.push({
                type: 0,
                content: videoFile
              })
            }
          } else {
            zongFileList.push(imgArrList[j])
          }
        } else {
          zongFileList.push(imgArrList[j])
        }
      }
      // 最终获取内容、图片、视频
      const fileListArr = zongFileList.filter(item => item.content !== '&nbsp;' && item.content != undefined)
      return fileListArr
    },
    handleSuccess(res, file) {
      if (res.code === 200) {
        const _that = this
        const shipinArr = ['video/mp4', 'video/m4v', 'video/3gp', 'video/mpg', 'video/avi', 'video/wmv']
        let shipin = shipinArr.filter(item => item === res.data.contentType)
        let type = shipin && shipin.length > 0 ? 2 : 1
        if (type === 1) {
          let reader = new FileReader()
          reader.readAsDataURL(file.raw) // 必须用file.raw
          reader.onload = () => { // 让页面中的img标签的src指向读取的路径
            let img = new Image()
            img.src = reader.result
            img.onload = () => {
              if (img.width > 500) {
                let scales = img.width/img.height
                img.style.width = '500px'
                img.style.height = 500 / scales + 'px'
              }
              img.setAttribute('links', res.data.path);
              _that.textContent = img
              _that.insertHtmlAtCaret(_that.textContent)
            }
          }
        } else if (type === 2) {
          let reader = new FileReader();
          reader.readAsDataURL(file.raw); // 必须用file.raw
          reader.onload = ()=> { // 让页面中的img标签的src指向读取的路径
            let video = document.createElement('video');
            video.src = reader.result;
            video.oncanplay = ()=>{
              video.setAttribute('width', 300);
              video.setAttribute('height', 200);
              video.setAttribute('links', res.data.path);
              video.style.objectFit = 'fill'
              video.style.display = 'inline-block'
              video.style.outline = 'none'
              video.setAttribute('controls', 'controls')
              _that.textContent = video
              _that.insertHtmlAtCaret(_that.textContent, '1')
            }
          };
        }
      } else {
        this.$message.error(res.msg || '上传失败!');
      }
      this.loading3 = false
    },
    beforeRichUpload(file){
      this.$refs.myRichText.focus()
      this.loading3 = true
      this.isShowHolder = true
      if (!this.selectText && !this.rangeNode) {
        this.selectText = window.getSelection();    
        this.rangeNode = this.selectText.getRangeAt(0);
        this.rangeNode.deleteContents();
      }
    },
    handError(err) {
      this.loading3 = false
      const errMsg = JSON.parse(err.message)
      this.$message.error(errMsg.message || errMsg.error || '操作超时请重试！');
    }
  }
}
</script>

<style scoped lang="less">
.placeholder-text{
  font-size: 14px;
  color: #CCCCCC;
  position: absolute;
  top: 15px;
  left: 15px;
}

.rich-text{
  width: 100%;
  width: 98%;
  height: 600px;
  min-height: 500px;
  border: 2px solid #F5F7F9;
  border-radius: 20px;
  box-sizing: border-box;
  padding: 15px;
  overflow: auto;
  resize: vertical;
  font-size: 14px;
  color: #333333;
  outline: none;
  user-select: none;
  position: relative;
}

.editor-custom-btn-container {
  position: absolute;
  bottom: 30px;
  left: 25px;
  .add-imgs{
    width: 76px;
    height: 76px;
    overflow: hidden;
    border-radius: 12px;
    border: 1px dashed #d9d9d9;
    position: relative;
    margin-right: 0px;
    margin-bottom: 0px;
    .add-img{
        width: 52px;
        height: 50px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        .img-log{
            width: 30px;
            height: 30px;
            background-image: url(../../../assets/icon30-2.png);
            background-repeat: no-repeat;
            background-position: -300px -121px;
            margin: auto;
        }
        .up-img{
            font-size: 12px;
            color: #999999;
        }
    }
    & /deep/ .avatar-uploaders .el-upload {
        width: 76px;
        height: 76px;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
  }
}
</style>